//
//  NSString+Add.m
//  PythonTestDemo
//
//  Created by admin on 2025/4/14.
//

#import "NSString+Add.h"

@implementation NSString (Add)

+ (NSString *)arrayToString:(NSArray<NSNumber *> *)arr; {
    if (arr.count < 5) return @""; // 安全检查

    // 从 index 1 获取有效长度、index 2 获取加减类型、index 3 开始是真正数据
    int count = arr[2].intValue;
    int flag = arr[3].intValue;
    BOOL isAdd = (arr[1].intValue % 2 == 0);
    
    // 边界检查，避免越界
    if (arr.count < 4 + count) return @"";
    NSMutableArray<NSNumber *> *result = [NSMutableArray arrayWithCapacity:count];
    for (NSInteger i = 0; i < count; i++) {
        int v = arr[4 + i].intValue;
        if (isAdd) {
            v -= flag;
            if (v < 0) v += 256;
        } else {
            v += flag;
            if (v > 255) v -= 256;
        }
        [result addObject:@(v)];
    }
    
    NSMutableData *mutableData = [NSMutableData data];
    for (NSNumber *num in result) {
        uint8_t byte = num.unsignedCharValue;
        [mutableData appendBytes:&byte length:1];
    }

    NSString *restoredStr = [[NSString alloc] initWithData:mutableData encoding:NSUTF8StringEncoding];
    
    return restoredStr; // 返回不可变数组
}

@end
